/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 26727
 * Date: 2024-07-08
 * Time: 9:37
 */
class Solution26 {
    int[] dx = {1,-1,0,0};
    int[] dy = {0,0,1,-1};
    int m,n;
    int[][] memo;
    public int longestIncreasingPath(int[][] matrix) {
        m = matrix.length;
        n = matrix[0].length;
        memo = new int[m][n];
        int ret = 0;
        for(int i = 0; i < m; i++) {
            for(int j = 0; j < n; j++) {
                ret = Math.max(ret,dfs(matrix,i,j));
            }
        }
        return ret;
    }

    int dfs(int[][] matrix,int i, int j) {
        int count = 1;
        if(memo[i][j] != 0) {
            return memo[i][j];
        }
        for(int k = 0; k < 4; k++) {
            int x = i+dx[k],y = j+dy[k];
            if(x >= 0 && x < m && y >= 0 && y < n && matrix[i][j] < matrix[x][y]) {
                count = Math.max(count,dfs(matrix,x,y)+1);
            }
        }
        memo[i][j] = count;
        return count;
    }
}
